package com.lehecai.core.lottery.fetcher.lotterydraw.impl.worker;

import com.lehecai.core.lottery.LotteryType;
import com.lehecai.core.lottery.fetcher.lotterydraw.LotteryDraw;
import com.lehecai.core.util.CharsetConstant;
import com.lehecai.core.util.CoreFetcherUtils;
import org.apache.commons.lang.StringUtils;
import org.dom4j.*;

import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

/**
 * 天津快乐10分钟 官方开奖结果抓取
 * 地址: http://www.tjflcpw.com/xml/kl10Prize.xml
 * @author zhangzq
 *
 */
public class LotteryDrawFetch568WorkerOfficial extends AbstractLotteryDrawFetchWorker {

    private static final String BASE_URL = "http://www.tjflcpw.com/xml/kl10Prize.xml";

    public LotteryDrawFetch568WorkerOfficial(LotteryType lotteryType) {
        super(lotteryType);
    }

    @Override
    public LotteryDraw fetchResult(String phase) {
        return this.fetchResultDetail(phase);
    }

    @Override
    @SuppressWarnings("unchecked")
    public LotteryDraw fetchResultDetail(String phase) {
        LotteryType lotteryType = this.getLotteryType();
        String fetchUrl = this.getResultDetailUrl(phase);
        LotteryDraw lotteryDraw = new LotteryDraw();
        if (StringUtils.isEmpty(fetchUrl)) {
            logger.error("==详细页面==抓取=={}==期号：{}==详细地址不存在，返回null", lotteryType.getName(), phase);
            return null;
        }
        try {
            String data;
            Map<String, String> headerParams = new HashMap<String, String>();
            headerParams.put("User-Agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/34.0.1847.131 Safari/537.36");
            headerParams.put("Content-Type","application/x-www-form-urlencoded");
            try {
                data = CoreFetcherUtils.URLGet(fetchUrl, headerParams, CharsetConstant.CHARSET_UTF8);
            } catch (Exception e) {
                logger.error("获取xml数据失败" + e.getMessage());
                return null;
            }
            if (StringUtils.isEmpty(data) || data.indexOf("404 Not Found") > 0) {
                logger.error(fetchUrl + "data is null or 404 Not Found");
                logger.error("未获取到开奖详情信息列表！");
                return null;
            }

            Document document = null;
            try {
                document = DocumentHelper.parseText(data);
            } catch (DocumentException e) {
                logger.error("解析开奖信息出现异常");
                logger.error(e.getMessage(), e);
            }

            //如果传入的彩期为null 则默认取最新一期的数据
            boolean isCurrentPhase = false;
            if (StringUtils.isEmpty(phase)) {
                isCurrentPhase = true;
            }
            Element root = null;
            List<Element> elements = null;
            if (document != null) {
                root = document.getRootElement();
            }
            if (root != null) {
                elements = root.elements();
            }
            if (elements != null) {
                for (Iterator<Element> it = elements.iterator(); it.hasNext();) {
                    Element element = it.next();
                    Element codeElement = element.element("code");
                    Element termElement = element.element("term");
                    Element drawOpenDateElement = element.element("drawOpenDate");
                    Element drawSaleCountElement = element.element("drawSaleCount");
                    String code = codeElement.getText();
                    String lotteryPhase = termElement.getText();
                    String drawOpenDate = drawOpenDateElement.getText();
                    if (StringUtils.isNotEmpty(drawOpenDate) && StringUtils.isNotEmpty(lotteryPhase)) {
                        drawOpenDate =  getDrawTime(lotteryPhase, drawOpenDate);
                    }
                    String drawSaleCount = drawSaleCountElement.getText();
                    if (StringUtils.isNotEmpty(drawSaleCount)) {
                        drawSaleCount = drawSaleCount.replace(",", "");
                    }
                    //取最后一条
                    if ((isCurrentPhase && !it.hasNext()) || phase.equals(lotteryPhase)) {
                        lotteryDraw.setPhase(lotteryPhase);
                        lotteryDraw.setResult(code.trim());
                        lotteryDraw.setTimeDraw(drawOpenDate);
                        lotteryDraw.setLotteryType(getLotteryType());
                        lotteryDraw.setVolumeOfSales(drawSaleCount);
                        break;
                    }
                }
            }
        } catch (Exception e) {
            logger.error("抓取开奖信息出现异常！");
            logger.error(e.getMessage(), e);
        }
        if (lotteryDraw.getPhase() == null) {
            return null;
        }
        return lotteryDraw;
    }

    @Override
    protected String getResultDetailUrl(String phase) {
        return BASE_URL;
    }

    @Override
    protected String getResultUrl(String phase) {
        return null;
    }

    private String getDrawTime(String lotteryPhase, String drawOpenDate) {
        if (lotteryPhase == null || "".equals(lotteryPhase) || lotteryPhase.length() < 7) {
            return "";
        }
        StringBuilder drawTime = new StringBuilder("");
        drawTime.append(lotteryPhase.substring(0, 4)).append("-").append(lotteryPhase.substring(4,6)).append("-").append(lotteryPhase.substring(6,8)).append(" ");
        drawTime.append(drawOpenDate).append(":00");
        return drawTime.toString();
    } 
}
